// pages/programme/create-programme/createProgramme.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight: app.globalData.navBarHeight,
    statusBarHeight: app.globalData.statusBarHeight,
    page: {
      currentPage: 1,
      pageSize: 10,
      total: 0,
    },
    productName: '',
    allSelectList: [],
    title: '新建方案',
    id: '',
    userName: '',
    productId: '',
    customerId: '',
    callback: '',
    type: 'add',
    presentationList: [],
    scrollTop: 0,
    startPageY: 0,
    hasScroll: true,
    flag:false,
    itemHeight: 90
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.callback)
    console.log(options)
    wx.setNavigationBarTitle({
      title: options.type === 'add' ? '新建方案' : '编辑方案'
    })
    this.setData({
      title: options.type === 'add' ? '新建方案' : '编辑方案',
      navBarHeight: app.globalData.navBarHeight,
      statusBarHeight: app.globalData.statusBarHeight,
      type: options.type,
      userName: options.userName,
      customerId: options.customerId ? options.customerId : '',
      productName: options.productName ? options.productName : '',
      productId: options.productId,
      callback: options.callback
    })
    if (options.type === 'add') {
      let allSelectList = JSON.parse(decodeURIComponent(options.allSelectList))
      this.setData({
        presentationList: allSelectList
      })
      console.log(allSelectList)
    } else {
      // 如果是查看编辑和直接选择素材编辑
      if (options.productId) {
        this.setData({
          productId: options.productId,
          productName: options.productName
        })
        if (options.allSelectList) {
          this.setData({
            allSelectList: JSON.parse(decodeURIComponent(options.allSelectList))
          })
        }
        this.getProgrammeDetail()
      } else {
        // 如果是选择添加为方案
        let allSelectList = JSON.parse(decodeURIComponent(options.allSelectList))
        this.setData({
          presentationList: allSelectList
        })
      }
    }
    this.getWxmlCode('#moveBox',(resp)=>{
      console.log(resp)
      this.setData({moveBox:resp})
      setTimeout(() => {
        this.getWxmlCode('#movelist0',(res)=>{
          this.setData({movelist0:res})
          console.log(res.top, resp.top, res.bottom)
          var space = res.top-resp.top
          var half = res.bottom - res.top + space
          console.log(resp.top, res.bottom, res.top)
          this.setData({
              itemHeight: 90,
              space: half, //两条中间到另一条的距离
              beLeftSpace: resp.top-(res.bottom - res.top)/2, //位置要减去距离
            })
          })
      },300)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      'page.currentPage': 1
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  reback () {
    wx.navigateBack({delta: 1})
  },
  getProgrammeDetail: function () {
    app.api.post({
      url: 'recommend_plan_detail',
      data: { productId: this.data.productId }
    }).then(res => {
      if (this.data.productName) {
        let allSelectList = this.data.allSelectList
        this.setData({
          presentationList: allSelectList,
          productName: this.data.productName
        })
      } else {
        let arr = []
        if (res.presentationDetailResps.length > 0) {
          arr = res.presentationDetailResps
          arr.forEach((v) => {
            v.active = true
          })
          this.setData({
            presentationList: arr,
            productName: res.productName
          })
        } else {
          this.setData({
            presentationList: [],
            productName: ''
          })
        }
      }
    })
  },
  selectProgramme () {
    let presentationList = []
    this.data.presentationList.forEach((v, k) => {
      if (v.active) {
        presentationList.push(v)
      }
    })
    let allSelectList = encodeURIComponent(JSON.stringify(presentationList))
    wx.redirectTo({
      url: `/pages/programme/select-material/selectMaterial?allSelectList=${allSelectList}&productId=${this.data.productId}&productName=${this.data.productName}&type=${this.data.type}`,
    })
  },
  // 编辑的去演示
  toDemonstration () {
    let presentationIds = []
    let presentationArr = []
    if (!this.data.productName) {
      wx.showToast({
        title: '请输入方案名称',
        icon: 'none',
        duration: 2000
      })
      return
    }
    this.data.presentationList.forEach((v) => {
      if (v.id && v.active) {
        presentationIds.push(v.id)
        const {id, presentationName, description} = v
        presentationArr.push({id, presentationName, description})
      }
    })
    if (presentationIds.length > 0) {
      let params = {
        productPresentationReqs: presentationArr,
        productName: this.data.productName,
      }
      if (!this.data.productId) {
        app.api.post({
          url: 'recommend_plan_save',
          data: params
        }).then(res => {
          if (presentationIds.length === 1) {
            if (this.data.presentationList[0].materialType === 'link') {
              wx.navigateTo({ url: `/pages/home-page/watch-project/watchProject?url=${encodeURIComponent(this.data.presentationList[0].url)}` })
            } else {
              wx.navigateTo({
                url: `/pages/home-page/to-demonstration/toDemonstration?from=material&type=demonstration&presentationIds=${presentationIds}&save=false&&productId=${res.data}`
              }) 
            }
          } else {
            wx.navigateTo({
              url: `/pages/home-page/to-demonstration/toDemonstration?from=material&type=demonstration&presentationIds=${presentationIds}&save=false&&productId=${res.data}`
            })
          }
        })
      } else {
        params.productId = this.data.productId
        app.api.post({
          url: 'recommend_plan_save',
          data: params
        }).then(res => {
          if (presentationIds.length === 1) {
            if (this.data.presentationList[0].materialType === 'link') {
              wx.navigateTo({ url: `/pages/home-page/watch-project/watchProject?sensors_ext=${code}&url=${encodeURIComponent(this.data.presentationList[0].url)}` })
            } else {
              wx.navigateTo({
                url: `/pages/home-page/to-demonstration/toDemonstration?from=material&type=demonstration&presentationIds=${presentationIds}&save=false&productId=${this.data.productId}`
              }) 
            }
          } else {
            wx.navigateTo({
              url: `/pages/home-page/to-demonstration/toDemonstration?from=material&type=demonstration&presentationIds=${presentationIds}&save=false&productId=${this.data.productId}`
            })
          }
        })
      }
    } else {
      wx.showToast({
        title: '请选择演示素材',
        icon: 'none',
        duration: 2000
      })
    }
  },
  startProgramme (e) {
    let { id } = e.currentTarget.dataset.item
    this.data.recommendList.forEach((v, k) => {
      if (id === v.id) {
        if (v.active) {
          v.active = false
        } else {
          v.active = true
        }
      }
    })
    this.setData({
      recommendList: this.data.recommendList
    })
  },
  recommendToggle (e) {
    let { id } = e.currentTarget.dataset.item
    this.data.presentationList.forEach((v, k) => {
      if (id === v.id) {
        if (v.active) {
          v.active = false
        } else {
          v.active = true
        }
      }
    })
    this.setData({
      presentationList: this.data.presentationList
    })
  },
  input (e) {
    this.setData({
      productName: e.detail.value
    })
  },
  save () {
    if (!this.data.productName) {
      wx.showToast({
        title: '请输入方案名称',
        icon: 'none',
        duration: 2000
      })
      return
    }
    let productPresentationReqs = []
    this.data.presentationList.forEach((v, k) => {
      if (v.active) {
        const {id, presentationName, description} = v
        productPresentationReqs.push({id, presentationName, description})
      }
    })
    if (productPresentationReqs.length === 0) {
      wx.showToast({
        title: '请选择演示素材',
        icon: 'none',
        duration: 2000
      })
      return
    }
    let params = {
      productPresentationReqs: productPresentationReqs,
      productName: this.data.productName,
    }
    let code = this.data.productId ? '03-00' : '03-01'
    if (!this.data.productId) {
      app.api.post({
        url: 'recommend_plan_save',
        data: params
      }).then(res => {
        console.log(res)
        wx.showToast({
          title: '保存成功',
          icon: 'none',
          duration: 2000
        })
        if (this.data.callback) {
          wx.redirectTo({
            url: `/pages/live-demonstration/liveDemonstration?callback=${this.data.callback}`
          })
        } else {
          wx.navigateBack({delta: 1})
        }
      })
    } else {
      delete params.customerId
      params.productId = this.data.productId
      app.api.post({
        url: 'recommend_plan_save',
        data: params
      }).then(res => {
        console.log(res)
        wx.showToast({
          title: '保存成功',
          icon: 'none',
          duration: 2000
        })
        if (this.data.callback) {
          wx.redirectTo({
            url: `/pages/live-demonstration/liveDemonstration?callback=${this.data.callback}`
          })
        } else {
          wx.navigateBack({delta: 1})
        }
      })
    }
  },
  listItemlongtap (e) {
    console.log('长按', e)
    this.setData({
      flag:true,
      hasScroll:false
    })
  },
  listItemStart (e) {
    console.log(e)
    this.setData({
      startPageY: e.touches[0].pageY
    })
    console.log(e.touches[0].pageY, this.data.itemHeight)
  },
  listItemMove (e) {
    if(this.data.flag){
      if (e.touches[0].pageY < this.data.itemHeight) {
        return false
      }
      console.log(e.touches[0].pageY, this.data.scrollTop)
      var moveTop = ((e.touches[0].pageY + this.data.scrollTop)-this.data.itemHeight - 172)
      if (moveTop < 0) {
        moveTop = 0
      }
      console.log(moveTop)
      var moveoutIndex = parseInt((moveTop+45)/this.data.itemHeight)
      console.log(moveoutIndex)
      this.moveoutIndex = moveoutIndex
      this.setData({nowmoveIndex:e.currentTarget.dataset.index,moveTop,moveoutIndex})
    }
  },
  scroll (e) {
    // console.log(e.detail.scrollTop)
    this.setData({
      scrollTop: e.detail.scrollTop
    })
  },
  listItemEnd(e){
    if (!this.data.flag) {
      return;
    }
    console.log(e.currentTarget.dataset.index, this.moveoutIndex)
    if (this.data.startPageY === e.changedTouches[0].pageY) {
      return false
    }
    let index = e.currentTarget.dataset.index
    let presentationList = this.data.presentationList
    let data = {...presentationList[index]}
    presentationList.splice(index,1)
    presentationList.splice(this.moveoutIndex,0,data)
    this.setData({presentationList:presentationList,moveoutIndex:-1,nowmoveIndex:-1, flag: false, hasScroll:true})
  },
  getWxmlCode(str,cal){
    const query = wx.createSelectorQuery()
    query.select(str).boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res) => {
    if(cal) cal(res[0])
    })
  }
})